package com.jw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.system.entity.GoodsCategory;
import com.jw.system.entity.User;
import com.jw.system.entity.vo.GoodsCategoryVO;
import com.jw.system.entity.vo.UserVO;
import com.jw.system.mapper.GoodsCategoryMapper;
import com.jw.system.mapper.MenuMapper;
import com.jw.system.service.GoodsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jw.utils.CategoryTreeBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品分类表 服务实现类
 * </p>
 *
 * @author jw
 * @since 2021-04-20
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements GoodsCategoryService {

    @Autowired
    private GoodsCategoryMapper catMapper;

    @Override
    public Page<GoodsCategoryVO> getCatList(Integer current, Integer size) {
        if(current == null){
            current = 1;
            size = catMapper.selectCount(null);
        }
        Page<GoodsCategory> page = new Page<>(current, size);
        //获得总分类列表
        List<GoodsCategory> catList = catMapper.selectList(null);
        List<GoodsCategoryVO> allCat =  new ArrayList<>();
        for(GoodsCategory cat : catList){
            GoodsCategoryVO categoryVO = new GoodsCategoryVO();
            BeanUtils.copyProperties(cat, categoryVO);
            allCat.add(categoryVO);
        }
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper();
        queryWrapper.eq("pid",0);
        Page<GoodsCategory> catRootPage = catMapper.selectPage(page, queryWrapper);
        //获得一级分类
        List<GoodsCategoryVO> tree =  new ArrayList<>();
        for(GoodsCategory cat : catRootPage.getRecords()){
            GoodsCategoryVO categoryVO = new GoodsCategoryVO();
            BeanUtils.copyProperties(cat, categoryVO);
            categoryVO.setLev(1);
            categoryVO.setChildren(CategoryTreeBuilder.getChild(categoryVO,allCat));
            tree.add(categoryVO);
        }
        Page<GoodsCategoryVO> catTree = new Page<>();
        catTree.setTotal(catRootPage.getTotal());
        catTree.setRecords(tree);
        return catTree;
    }
}
